document.addEventListener('DOMContentLoaded', () => {
    const authorInput = document.getElementById('author-input');
    const messageInput = document.getElementById('message-input');
    const submitBtn = document.getElementById('submit-btn');
    const messageList = document.getElementById('message-list');
    const noMessageTip = document.getElementById('no-message-tip');

    // 从 localStorage 加载留言
    let messages = JSON.parse(localStorage.getItem('messages')) || [];

    // 渲染所有留言
    function renderMessages() {
        messageList.innerHTML = ''; // 清空现有留言
        if (messages.length === 0) {
            noMessageTip.classList.remove('hidden');
        } else {
            noMessageTip.classList.add('hidden');
            messages.forEach((msg, index) => {
                const messageItem = document.createElement('div');
                messageItem.className = 'message-item';
                messageItem.innerHTML = `
                    <div class="meta">
                        <span class="author">${msg.author}</span>
                        <span class="timestamp">${msg.timestamp}</span>
                        <button class="delete-btn" data-index="${index}">删除</button>
                    </div>
                    <p class="content">${msg.content}</p>
                `;
                messageList.prepend(messageItem); // 新留言放在最上面
            });
        }
    }

    // 保存留言到 localStorage
    function saveMessages() {
        localStorage.setItem('messages', JSON.stringify(messages));
    }

    // 处理留言提交
    submitBtn.addEventListener('click', () => {
        const author = authorInput.value.trim();
        const content = messageInput.value.trim();

        if (author && content) {
            const newMessage = {
                author: author,
                content: content,
                timestamp: new Date().toLocaleString()
            };
            messages.push(newMessage);
            saveMessages();
            renderMessages();
            
            // 清空输入框
            authorInput.value = '';
            messageInput.value = '';
        } else {
            alert('名字和留言内容都不能为空！');
        }
    });

    // 处理留言删除
    messageList.addEventListener('click', (e) => {
        if (e.target.classList.contains('delete-btn')) {
            const index = e.target.getAttribute('data-index');
            if (confirm('确定要删除这条留言吗？')) {
                messages.splice(index, 1);
                saveMessages();
                renderMessages();
            }
        }
    });

    // 页面加载时立即渲染
    renderMessages();
});